package ext.acae2.change.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import wt.doc.WTDocument;
import wt.enterprise.RevisionControlled;
import wt.fc.Persistable;
import wt.fc.WTReference;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.util.WTException;
import wt.util.WTMessage;

import com.ptc.core.meta.common.TypeIdentifierHelper;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.core.ui.validation.DefaultUIComponentValidator;
import com.ptc.core.ui.validation.UIValidationCriteria;
import com.ptc.core.ui.validation.UIValidationFeedbackMsg;
import com.ptc.core.ui.validation.UIValidationKey;
import com.ptc.core.ui.validation.UIValidationResult;
import com.ptc.core.ui.validation.UIValidationStatus;
import com.ptc.netmarkets.model.NmOid;

import ext.acae2.ACAEConstants;
import ext.acae2.change.helper.ChangeTaskHelper;
import ext.acae2.change.resource.ECNResource;

/**
 * @desription 
 *  ECN Implemention plan check
 * @author cnie
 * @date 2013-5-13 上午11:13:56
 */
public class CreateChangeTaskValidator extends DefaultUIComponentValidator{
	
	private static final  Logger LOGGER =  LogR.getLogger(CreateChangeTaskValidator.class.getName());
	
	private static final String RESOURCE = ECNResource.class.getName();
	
	
	
	@Override
	public UIValidationResult validateFormSubmission(UIValidationKey uiValidationKey,
			UIValidationCriteria uivalidationcriteria, Locale local) throws WTException {
		UIValidationResult uivalidationresult = UIValidationResult.newInstance(uiValidationKey, UIValidationStatus.PERMITTED);
		String ecnType = uivalidationcriteria.getTextParameter("ecnType");
		if(StringUtils.isNotBlank(ecnType)){
			if (ecnType.indexOf(ACAEConstants.ACAE2_TYPE_FILE_ECN) < 0
					&& ecnType.indexOf(ACAEConstants.ACAE2_TYPE_PARTDRAWING_ECN) < 0) {
				return uivalidationresult;
			}
		}
//		java.util.Map map = uivalidationcriteria.getParameterMap();
//		java.util.Map map1 = uivalidationcriteria.getFormData();
//		String changeMode = ((String[]) map.get("changeMode"))[0];
//		String[] affectedTableId = (String[]) map.get("tableID");
		LOGGER.debug("--> start ImplPlanValidator");
		
//		WTReference objRef = uivalidationcriteria.getSelectedRowObject();
//		LOGGER.debug(objRef+"===============uialidationCriteria.getContextObject()");
//		if(objRef==null){
//			List<NmOid> initItemList = uivalidationcriteria.getInitialItemsByName("changeTask_affectedItems_table");
//			objRef = initItemList.get(0).getWtRef();
//		}
		String errorStr = null;
		
		List<NmOid> initItemList = uivalidationcriteria.getInitialItemsByName("changeTask_affectedItems_table");
		WTReference objRef = initItemList.get(0).getWtRef();
		
		List<NmOid> rmItemList = uivalidationcriteria.getRemovedItemsByName("changeTask_affectedItems_table");
		Persistable p =null;
		if(rmItemList.contains(initItemList.get(0))){
			p = objRef.getObject();
			if(p instanceof RevisionControlled){
				RevisionControlled rc=(RevisionControlled)p;
				errorStr = WTMessage.getLocalizedMessage(RESOURCE, ECNResource.AFFECTED_ITEM_REMOVE_ERROR,new Object[]{rc.getName()},local);
			}
		}else{
			//uialidationCriteria.setContextObject(objRef);
			p = objRef.getObject();
			String affectedItemType = TypeIdentifierHelper.getType(p).toExternalForm();
			LOGGER.debug(affectedItemType+"===============affectedItemType");
			List<NmOid> addItemList = uivalidationcriteria.getAddedItemsByName("changeTask_resultingItems_table");
			
			if(addItemList==null||addItemList.size()==0){
				errorStr = WTMessage.getLocalizedMessage(RESOURCE, ECNResource.NO_RESULT_ITEM_ERROR,null,local);
			}else{
				NmOid nmoid = NmOid.newNmOid(p.getPersistInfo().getObjectIdentifier());
				if(nmoid.isA(WTDocument.class)){
					
					WTDocument primaryDoc = (WTDocument) nmoid.getWtRef().getObject();
					//String[] resultItemOidArr = resultItemOids.split("#");
					if(addItemList!=null&&addItemList.size()>1){
						errorStr = WTMessage.getLocalizedMessage(RESOURCE, ECNResource.RESULT_ITEM_COUNT_ERROR,null,local);
					}else{
						boolean isPrimaryResultItem = ChangeTaskHelper.checkFileECNResultItem(primaryDoc,addItemList);
						if(!isPrimaryResultItem){
							String[] params = new String[]{primaryDoc.getNumber()};
							errorStr = WTMessage.getLocalizedMessage(RESOURCE, ECNResource.NO_PRIMARY_DOC_RESVIED_ERROR,params,local);
						}
					}
				}else {
					if(nmoid.isA(WTPart.class)){
						WTPart primaryPart = (WTPart) nmoid.getWtRef().getObject();
						List<RevisionControlled> releatedItems = new ArrayList<RevisionControlled>();
						releatedItems = ChangeTaskHelper.getPrimaryRelectedCADDocs(primaryPart, releatedItems);
						boolean isPrimaryRelatedItem = ChangeTaskHelper.checkPartECNResultItem(addItemList, releatedItems);
						if(!isPrimaryRelatedItem)
							errorStr = WTMessage.getLocalizedMessage(RESOURCE, ECNResource.NO_PRIMARY_RELEATED_OBJ_RESVIED_ERROR,new Object[]{primaryPart.getName()},local);
					}
				}
			}
		}
		
		LOGGER.debug("--> end ImplPlanValidator");
		
		if(StringUtils.isNotBlank(errorStr)){
			uivalidationresult.setStatus(UIValidationStatus.DENIED);
			uivalidationresult.addFeedbackMsg(UIValidationFeedbackMsg.newInstance(errorStr, FeedbackType.ERROR));
		}
		
		return uivalidationresult;
	}
	
	
	
	
	

}
